package com.topisv.tms.web.workBox;

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.lightShelf.LightShelf;
import com.topisv.tms.entity.lightShelf.LightShelfStock;
import com.topisv.tms.entity.workBox.WorkBox;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.lightShelf.LightShelfService;
import com.topisv.tms.service.lightShelf.LightShelfStockService;
import com.topisv.tms.service.workBox.WorkBoxService;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseController;

/**
 * 流转箱_control
 * @author ch
 */
@Controller
@RequestMapping({ "/workBox" })
public class WorkBoxController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(WorkBoxController.class);

	@Autowired
	private LightShelfService lightShelfService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private LightShelfStockService lightShelfStockService;
	@Autowired
	private WorkBoxService workBoxService;
	
	
	/**
	 * 导向流转箱管理页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toWorkBoxMgrPage")
	public String toWorkBoxMgrPage(ServletRequest request,HttpServletResponse response,Model model){
		
		
		//查找商户组
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		User user=this.accountService.findUserByJobuuid(curUser.jobuuid);
		List<Customers> customerList;
		if(user.getUserType().equals("paiu")){ //派友用户
		    customerList=this.customersService.findAll();
			model.addAttribute("customerList",customerList);
		}else if(user.getUserType().equals("customer")){ //商家用户
			customerList=new ArrayList<Customers>();
			String customerCode=curUser.customerCode;
		    Customers customer=this.customersService.findByCustomerCode(customerCode);
			customerList.add(customer);
			model.addAttribute("customerList",customerList);
			model.addAttribute("customer", customer); 
		}
	    
		return "workBox/workBoxMgr";
	}
	
	//查询流转箱
	@RequestMapping(value = "v2_queryWorkBox")
	public String queryWorkBox(Model model, ServletRequest request) {
		try {
			
			//查找商户组
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			User user=this.accountService.findUserByJobuuid(curUser.jobuuid);
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			
			String customerCode=(String) param.get("customerCode");
			String warehouseCode=(String) param.get("warehouseCode");
			fillSelectValue(model, customerCode);
			List<Customers> customerList;
			if(user.getUserType().equals("paiu")){ //派友用户
			    customerList=this.customersService.findAll();
				model.addAttribute("customerList",customerList);
			}else if(user.getUserType().equals("customer")){ //商家用户
				customerList=new ArrayList<Customers>();
			    Customers customer=this.customersService.findByCustomerCode(customerCode);
				customerList.add(customer);
				model.addAttribute("customerList",customerList);
				model.addAttribute("customer", customer); 
			}
			
			List<WorkBox> workBoxList = this.workBoxService.loadByCondition(customerCode,warehouseCode);
			model.addAttribute("workBoxList", workBoxList);
			
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "workBox/workBoxMgr";
	}
	
	/**
	 * 创建流转箱
	 * @param bill
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "ajaxCreateWorkBox")
	@ResponseBody
	public String ajaxCreateWorkBox(HttpServletResponse response,ServletRequest request) {
		try {
			
			String boxName=request.getParameter("boxName");
			String customerCode=request.getParameter("customerCode");
			String warehouseCode=request.getParameter("warehouseCode");
			
		    WorkBox box=new WorkBox();
		    box.setCustomerCode(customerCode);
		    box.setWarehouseCode(warehouseCode);
		    
		    Random r=new Random();
			DecimalFormat df=new DecimalFormat("0000");
			String boxCode=null;
			while(true){
				String temp=df.format(r.nextInt(9999));
				boxCode="B"+warehouseCode+temp;
				WorkBox tempBox=this.workBoxService.loadBoxByCode(boxCode);
				if(tempBox==null){
					break;
				}
			}
			box.setBoxCode(boxCode);
		    
		    
		    box.setBoxName(boxName);
		    box.setStatus("free");
		    
		    this.workBoxService.save(box);
			
			return "true";
			
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 删除
	 * @param lightShelfId 灯光架ID
	 * @return
	 */
	@RequestMapping(value = "ajaxDelete")
	@ResponseBody
	public String ajaxDelete(HttpServletResponse response,ServletRequest request) {
		try {
			Long boxId=Long.valueOf(request.getParameter("boxId"));
			this.workBoxService.delete(boxId);
			return "true";
			
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 释放
	 * @param lightShelfId 灯光架ID
	 * @return
	 */
	@RequestMapping(value = "ajaxFree")
	@ResponseBody
	public String ajaxFree(HttpServletResponse response,ServletRequest request) {
		try {
			Long boxId=Long.valueOf(request.getParameter("boxId"));
			this.workBoxService.free(boxId);
			return "true";
			
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 查询灯光架详细信息
	 * @param lightShelfId 灯光架ID
	 * @return
	 */
	@RequestMapping(value = "ajaxLoadLightShelfDetail")
	public void ajaxLoadLightShelfDetail(HttpServletResponse response,ServletRequest request) {
		try {
			Long lightShelfId=Long.valueOf(request.getParameter("lightShelfId"));
			LightShelf lightShelf=this.lightShelfService.loadLightShelfById(lightShelfId);
			List<LightShelfStock> stockList=this.lightShelfStockService.loadStock(lightShelf.getId());
			
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("lightShelf", lightShelf);
			map.put("stockList", stockList);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
			
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
}